package com.codetile.batch.file;

import com.codetile.batch.db.User;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.xml.StaxEventItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.xstream.XStreamMarshaller;

import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableBatchProcessing
public class XmlItemReaderDemo {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    @Qualifier("dbJdbcWrite")
    private ItemWriter<? super User> dbWrite;

    @Bean
    public Job xmlJob(){
        return jobBuilderFactory.get("xmlJob")
                .start(xmlStep())
                .build();
    }

    @Bean
    public Step xmlStep(){
        return stepBuilderFactory.get("xmlStep")
                .<User,User>chunk(2)
                .reader(xmlReader())
                .writer(dbWrite)
                .build();
    }

    @Bean
    @StepScope
    public StaxEventItemReader<User> xmlReader(){
        StaxEventItemReader<User> reader=new StaxEventItemReader<>();
        reader.setResource(new ClassPathResource("user.xml"));
        //指定根标签
        reader.setFragmentRootElementName("user");
        XStreamMarshaller streamMarshaller=new XStreamMarshaller();
        Map<String,Class> map=new HashMap<>();
        map.put("user",User.class);

        streamMarshaller.setAliases(map);
        reader.setUnmarshaller(streamMarshaller);
        return reader;
    }

}
